package com.czk.springboot.reactive.webflux.controller;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.http.codec.multipart.FilePart;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebSession;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.time.Duration;

/**
 * @Author: chenzhangkun
 * @CreateTime: 2025-05-23
 * @Description:
 * @Version: 1.0
 */
@RestController
public class HelloController {
    /**
     * webflux兼容了大部分传统的api
     *
     * @param name
     * @return
     */
    @GetMapping(value = "/hehe")
    public String hello(@RequestParam String name) {
        return name;
    }

    @GetMapping(value = "/haah")
    public Mono<String> haha() {
        return Mono.just("haha");
    }

    @GetMapping(value = "/flux")
    public Flux<String> flux() {
        return Flux.just("czk", "czj");
    }

    /**
     * sse的实现
     * 实现延迟推送的效果
     *
     * @return
     */
    @GetMapping(value = "/sse", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<Integer> sse() {
        return Flux.range(0, 10)
                .delayElements(Duration.ofSeconds(1L));

    }

    /**
     * 返回sse对象
     * @return
     */
    @GetMapping(value = "/sse1", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<ServerSentEvent<String>> sse1() {
        return Flux.range(0, 10)

                .map(i -> ServerSentEvent.<String>builder()
                        .id(String.valueOf(i))
                        .event("event-" + i)
                        .data("data-" + i)
                        .build()).delayElements(Duration.ofSeconds(1L));
    }

    public Mono<Void> api(ServerWebExchange exchange,
                          WebSession webSession,
                          HttpMethod method,
                          HttpEntity<String> entity,
                          // 文件处理
                          FilePart filePart){
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String name = method.name();

        return Mono.empty();
    }

}
